package com.wn.icloud.provider.uac.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wn.icloud.biz.BaseBiz;
import com.wn.icloud.common.context.BaseContextHandler;
import com.wn.icloud.common.msg.ObjectRestResponse;
import com.wn.icloud.common.msg.TableResultResponse;
import com.wn.icloud.common.util.Query;
import com.wn.icloud.provider.uac.entity.EnterpriseHeadlines;
import com.wn.icloud.provider.uac.mapper.EnterpriseHeadlinesMapper;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.entity.Example;

import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class EnterpriseHeadlinesBiz extends BaseBiz<EnterpriseHeadlinesMapper, EnterpriseHeadlines> {

    public TableResultResponse<EnterpriseHeadlines> findByPage(Query query) {
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Example example = new Example(clazz);
        if(query.entrySet().size()>0) {
            Example.Criteria criteria = example.createCriteria();
            for (Map.Entry<String, Object> entry : query.entrySet()) {
                criteria.andLike(entry.getKey(), "%" + entry.getValue().toString() + "%");
            }
        }
        example.orderBy("publishTime").desc();
        Page<EnterpriseHeadlines> result = PageHelper.startPage(query.getPage(), query.getLimit());
        List<EnterpriseHeadlines> list = mapper.selectByExample(example);
        return new TableResultResponse<EnterpriseHeadlines>(result.getTotal(), list);
    }

    public ObjectRestResponse<EnterpriseHeadlines> addEnterpriseHeadlines(@RequestBody EnterpriseHeadlines enterpriseHeadlines) {
        enterpriseHeadlines.setPublishPersonal(BaseContextHandler.getUsername());
        enterpriseHeadlines.setPublishTime(new Date());
        this.insertSelective(enterpriseHeadlines);
        return new ObjectRestResponse<EnterpriseHeadlines>();
    }

    public ObjectRestResponse<EnterpriseHeadlines> updateEnterpriseHeadlines(@RequestBody EnterpriseHeadlines enterpriseHeadlines) {
        enterpriseHeadlines.setPublishPersonal(BaseContextHandler.getUsername());
        enterpriseHeadlines.setPublishTime(new Date());
        this.updateSelectiveById(enterpriseHeadlines);
        return new ObjectRestResponse<EnterpriseHeadlines>();
    }

    public void deleteByIds(String ids) {
        List<Integer> idList = Arrays.stream(ids.split(",")).map(Integer::valueOf).collect(Collectors.toList());
        idList.forEach(this::deleteById);
    }
}
